<template>
  <div class="card content-box">
    <span class="text">角色管理（待完善） 🍓🍇🍈🍉</span>

    <!--  文件上传  -->
    <el-upload
      ref="uploadRef"
      :auto-upload="false"
      :on-change="onChange"
      :show-file-list="false"
      :file-list="fileList"
    >
      <template #trigger>
        <el-button type="primary">选择文件</el-button>
      </template>
      <el-button class="ml-3" type="success" @click="submitUpload">
        upload to server
      </el-button>
      <template #tip>
        <div class="el-upload__tip">文件最大不能超过 1MB</div>
      </template>
    </el-upload>

    <el-divider></el-divider>

    <img style="height: 300px" :src="imgUrl" alt="" />
  </div>
</template>

<script setup lang="ts" name="roleManage">
import { ref } from 'vue'
import {
  ElMessage,
  UploadFile,
  UploadFiles,
  UploadInstance,
  UploadRawFile,
  UploadUserFile
} from 'element-plus'
import { uploadUniCloudFileApi } from '@/api/modules/upload'

const uploadRef = ref<UploadInstance>()
const fileList = ref<UploadUserFile[]>()
const fileData = ref({ fileName: '', base64: '' })
const imgUrl = ref<string>()

const beforeUpload = (rawFile: UploadRawFile) => {
  if (rawFile.size / 1024 / 1024 > 1) {
    ElMessage.error('文件最大不能超过 1MB！')
    return false
  }
  return true
}

const onChange = (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  if (!beforeUpload(uploadFile.raw!)) return

  const blob = new Blob([uploadFile.raw as File])
  const reader = new FileReader()
  reader.readAsDataURL(blob)
  reader.onload = (event: any) => {
    let base64 = event.target.result
    base64 = base64.split(',')[1]
    fileData.value.fileName = uploadFile.name
    fileData.value.base64 = base64
  }
}

const submitUpload = async () => {
  let res = await uploadUniCloudFileApi({
    params: fileData.value
  })
  if ((res as any).fileID) {
    imgUrl.value = (res as any).fileID
  }
}
</script>
